package com.zlsy.secondtime.threadcoreknowledge.sixstates;

/**
 * @author zhouliang
 * @date 2020/5/16 11:04
 * 展示线程的另外三种状态： Blocked 、 Waiting 、TimedWaiting
 */
public class BlockedWaitingTimedWaiting implements Runnable {

    @Override
    public void run() {
        try {
            sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private synchronized void sync() throws InterruptedException {
        Thread.sleep(1000);

        this.wait();
    }

    public static void main(String[] args) throws InterruptedException {
        BlockedWaitingTimedWaiting r1 = new BlockedWaitingTimedWaiting();

        Thread thread1 = new Thread(r1);
        Thread thread2 = new Thread(r1);

        thread1.start();
        //让线程1：先竞争到锁并且，进入 Thread.sleep
        Thread.sleep(10);
        thread2.start();


        //线程1正在执行Thread.sleep TimedWaiting
        System.out.println("线程1："+thread1.getState());
        //因为线程2想拿到sync的锁，但是线程1还没释放锁 Blocked
        System.out.println("线程2："+thread2.getState());
        Thread.sleep(1300);
        // WAITING
        System.out.println("线程1："+thread1.getState());
    }
}
